package photo;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import link.api.LinkApi;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import org.an.ku.base.adapter.BaseListAdapter;
import org.an.proj.contacts.config.LogUtil;
import org.an.proj.contacts.model.response.Result;
import org.an.proj.contacts.net.service.retrofit.call.SimpleCallback;
import org.an.proj.contacts.net.service.retrofit.upload.ProgressListener;
import org.an.proj.contacts.net.service.retrofit.util.ServiceGenerator;
import photo.view.UploadImageView;
import retrofit2.Call;

/**
 * 创建时间：2017年03月16日15:36 <br>
 * 作者：fuchaoyang <br>
 * 描述：
 */

public class UploadImgAdapter extends BaseListAdapter<UploadImageBean> {
  private static final String TAG = "UploadImgAdapter";
  private String mPositionTag;
  private int mMaxCount = 3;

  public void setPositionTag(String positionTag) {
    this.mPositionTag = positionTag;
  }

  public UploadImgAdapter(Context context) {
    super(context);
  }

  @Override public int getCount() {
    if (getDatas().size() < mMaxCount) {
      return getDatas().size() + 1;
    }
    return super.getCount();
  }

  public void onAddPhoto(List<String> paths) {
    for (int i = 0; i < paths.size(); i++) {
      UploadImageBean uploadImageBean = new UploadImageBean(paths.get(i));
      getDatas().add(uploadImageBean);
      upload(uploadImageBean);
    }
    notifyDataSetChanged();
  }

  /**
   * 更新过程，通过url拿到view，上传结束后，刷新adapter
   */
  public void upload(final UploadImageBean uploadImageBean) {
    /*Call<Result<UploadImgResultInfo>> mUploadImageCall =
        ServiceGenerator.createService(LinkApi.class, new ProgressListener() {
          @Override public void onProgress(final long currentBytes, final long contentLength,
              final boolean done) {

            final UploadImageView uploadImageView = uploadImageBean.imageView;
            if (uploadImageView == null) return;

            uploadImageView.post(new Runnable() {
              @Override public void run() {
                uploadImageBean.progress = (int) (100 * currentBytes / contentLength);
                uploadImageView.setUploadProgress(currentBytes, contentLength, done);
                LogUtil.e("upload",
                    String.format("onProgress:(%s,%s)", currentBytes, contentLength));
              }
            });
          }
        }).uploadImage(getRequestBodyParams("files", uploadImageBean.path));
    mUploadImageCall.enqueue(new SimpleCallback<Result<UploadImgResultInfo>>() {
      @Override public void onResponse(Call<Result<UploadImgResultInfo>> call,
          Result<UploadImgResultInfo> entity, boolean isSuccess) {
        if (hasData() && !TextUtils.isEmpty(entity.data.id)) {
          uploadImageBean.progress = 100;
          uploadImageBean.id = entity.data.id;
          //uploadImageBean.imageView.setState(UploadImageView.STATE_UPLOAD_FAILED);
          notifyDataSetChanged();
        } else {
          // 上传失败，更新UI
          uploadImageBean.progress = -1;
          notifyDataSetChanged();
        }
        *//*if (uploadImageBean.progress == 100) {
          ToastUtil.toast(MyApplication.getInstance(), R.string.str_upload_success);
        }*//*
      }
    });*/
  }

  private static Map<String, RequestBody> getRequestBodyParams(String filesName, String path) {
    File image = new File(path);
    RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), image);
    Map<String, RequestBody> params = new HashMap<>();
    //params.put("files\"; filename=\"upload.jpeg\"", requestBody);
    params.put(filesName + "\"; filename=\"upload.jpeg\"", requestBody);
    return params;
  }

  @Override public View getView(final int position, View convertView, ViewGroup parent) {
    // 场景没必要复用
    UploadImageView uploadImageView = new UploadImageView(getContext());
    if (position < getDatas().size()) {
      getItem(position).imageView = uploadImageView;
    }
    uploadImageView.setUploadImageListener(new UploadImageView.UploadImageListener() {
      @Override public void delImage(UploadImageView uploadImageView, String message) {
        getDatas().remove(position);
        notifyDataSetChanged();
      }

      @Override public void onImageClick(UploadImageView uploadImageView, int state) {
        switch (state) {
          case UploadImageView.STATE_ADD:
            //TakePhotoDialog dialog =
            //    new TakePhotoDialog((Activity) getContext(), mMaxCount - getDatas().size());
            //dialog.setTag(mPositionTag);
            //dialog.show();
            break;
          case UploadImageView.STATE_SHOW:
            break;
          case UploadImageView.STATE_UPLOAD_FAILED:
            // 失败重新上传
            upload(getItem(position));
            break;
        }
      }
    });

    if (position < getDatas().size()) {
      UploadImageBean imageBean = getItem(position);
      // 如果上面有设置setState，这里就不需要处理了
      if (imageBean.progress == -1) {
        uploadImageView.setState(UploadImageView.STATE_UPLOAD_FAILED);
      } else if (imageBean.progress == 100) {
        uploadImageView.setState(UploadImageView.STATE_SHOW);
      } else {
        if (imageBean.path == null) {
          uploadImageView.setState(UploadImageView.STATE_ADD);
        } else {
          uploadImageView.setState(UploadImageView.STATE_UPLOADING);
        }
      }

      if (!TextUtils.isEmpty(imageBean.url)) {
        uploadImageView.showImage(imageBean.path);
      } else if (!TextUtils.isEmpty(imageBean.path)) {
        uploadImageView.showImage(new File(imageBean.path));
      }
    }

    return uploadImageView;
  }
}
